package org.example.big_data.utils;

import java.io.*;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;

//开发为工具类，接受前端的文件流in和文件名ObjectName，上传到OSS服务器上
//返回给前端，文件在OSS服务器上的路径和文件名
public class AliOSSUtil {
    public static String uploadFile(String ObjectName,InputStream in) throws com.aliyuncs.exceptions.ClientException {
        //设计一个变量，用于存储返回的”文件在OSS上的存储地址“
        String url = "";
        // 设置 OSS Endpoint跟节点 和 Bucket 名称，去网页上找
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
//        String bucketName = generateUniqueBucketName("big-event-wjj");//防止重复调用generateUniqueBucket每次生成戈恩复杂的Bucket名，我们这里测试就采取一个固定的Bucket名
        String bucketName = "big-event-wjj";
        // 替换为您的 Bucket 区域
        String region = "cn-beijing";
        // 创建 环境变量实例，获取写在环境变量中的AccessKeyId和AccessKeySecret
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        //生成ossClient对象，用于与OSS服务器交互
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();

        try {
            // 1. 上传文件 objectName 为文件在OSS中的路径和文件名,由前端用户决定
            String objectName = ObjectName ;
            //测试：ossClient.putObject 上传文件，直接从参数中接收输入流和文件名
            ossClient.putObject(bucketName, objectName, in);
            System.out.println("文件 " + objectName + " 上传成功。");

            //返回给前端，文件在OSS服务器上的路径和文件名
            url = "https://"+bucketName+"."+"oss-cn-beijing.aliyuncs.com"+"/"+objectName;













        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (com.aliyun.oss.ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;}

}
